<template>
<div class="user">
  <div class="full-height" style="position: relative">
    <div class="bg">
      <div class="title" style="position: relative">
        <div id="user-version" style="position: absolute; top: 10px; right: 20px;color: #fff">{{ `V ${ version } ${ versionType }` }}</div>
        <div id="user-avatar">
          <!--<img v-if="userInfo.photoUrl !== '' && userInfo.photoUrl !== null" :src="userInfo.photoUrl" class="avatar">-->
          <div class="photo-box">
            <q-img
              class="photo"
              :src="userInfos.photoUrl"
              spinner-color="white"
            />
            <div class="absolute">
<!--              <div-->
<!--                v-if="!userInfos.photoUrl"-->
<!--                style="height: 130px; width: 100%; background: #d0d6fb;"-->
<!--              />-->
              <!-- <q-btn
                class="upload-btn"
                unelevated
                @click="_onUploadPhotoClick"
                :class="{ 'dashed-border': !userInfos.photoUrl }"
              >
                <q-icon
                  v-if="!userInfos.photoUrl"
                  size="50px"
                  name="iconfont icontubiao-61"
                  color="white"
                />
              </q-btn>
              <input
                ref="fileInput"
                type="file"
                style="display: none;"
                accept="image/png, image/jpeg"
                @change="onPhotoFileSelected"
              /> -->
            </div>
          </div>
        </div>
        <div style="font-size: 16px;margin-top: 8px">{{ userInfos && userInfos.name ? userInfos.name : '--' }}</div>
      </div>
    </div>
    <div class="body" id="user-info">
      <q-list bordered separator active-class="activated" style="border: none;margin: 0 20px;border-bottom: 1px solid rgba(0,0,0,0.12)">
        <q-item :clickable="false" style="padding: 0px 20%">
          <div class="row justify-around">
            <div class="col-4">
              <q-item-section>
                <span style="color: #5f77fd;display: inline-block" class="iconfont icontubiao-80">
                  <span style="color: black"> 公司名称</span>
                </span>
              </q-item-section>
            </div>
            <div class="col-4" style="text-align: right">
              <q-item-section>
                <span style="color: black"> {{ userInfos.companyName ? userInfos.companyName : '--' }}</span>
              </q-item-section>
            </div>
          </div>
        </q-item>
        <q-item :clickable="false" style="padding: 0px 20%">
          <div class="row justify-around">
            <div class="col-4">
              <q-item-section>
                <span style="color: #5f77fd;display: inline-block" class="iconfont icontubiao-81">
                  <span style="color: black"> 服务期限</span>
                </span>
              </q-item-section>
            </div>
            <div class="col-4" style="text-align: right">
              <q-item-section>
                <span style="color: #5f77fd;display: inline-block">
                  <!-- @click="showServiceTimeDialog" 查看期限,点击效果暂注 -->
                  <q-btn style="padding: 0px;margin-left: 10px;font-size: 16px;min-height: 0px"
                  @click="showServiceTimeDialog" flat color="primary" label="查看" />
                </span>
              </q-item-section>
            </div>
          </div>
        </q-item>
        <q-item :clickable="false" style="padding: 0px 20%">
          <div class="row justify-around">
            <div class="col-4">
              <q-item-section>
                <span style="color: #5f77fd;display: inline-block" class="iconfont icontubiao-1">
                  <span style="color: black"> 手机号码</span>
                </span>
              </q-item-section>
            </div>
            <div class="col-4" style="text-align: right">
              <q-item-section>
                <div style="color: #5f77fd;display: flex;align-items: center;justify-content: flex-end">
                  <span style="color: black;line-height: 28px"> {{ userInfos.phone ? userInfos.phone : '--' }}</span>
                  <q-btn v-if="certified" style="padding: 0px;font-size: 16px;min-height: 0px;margin-left: 20px" flat color="primary" label="更换手机号" @click="showChangePhone=true" />
                </div>
              </q-item-section>
            </div>
          </div>
        </q-item>
        <q-item :clickable="false" style="padding: 0px 20%">
          <div class="row justify-around">
            <div class="col-4">
              <q-item-section>
                <span style="color: #5f77fd;display: inline-block" class="iconfont icontubiao-84">
                  <span style="color: black"> 微信号码</span>
                </span>
              </q-item-section>
            </div>
            <div class="col-4" style="text-align: right">
              <q-item-section>
                <span v-if="userInfos.isWeChatConnected" style="color: #5f77fd;display: inline-block">
                  <span style="color: black"> 已绑定</span>
                  <q-btn style="padding: 0px;margin-left: 10px;font-size: 16px;min-height: 0px" flat color="primary" label="解绑" @click="outWechat" />
                </span>
                <span v-else style="color: #5f77fd;display: inline-block">
                  <q-btn style="padding: 0px;margin-left: 10px;font-size: 16px;min-height: 0px" flat color="primary" label="绑定" />
                </span>
              </q-item-section>
            </div>
          </div>
        </q-item>
        <q-item :clickable="false" style="padding: 0px 20%">
          <div class="row justify-around">
            <div class="col-4">
              <q-item-section>
                <span style="color: #5f77fd;display: inline-block" class="iconfont icontubiao-23">
                  <span style="color: black"> 姓名</span>
                </span>
              </q-item-section>
            </div>
            <div class="col-4" style="text-align: right">
              <q-item-section>
                <span style="color: #5f77fd;display: inline-block">
                  <span style="color: black"> {{ userInfos.name ? userInfos.name : '--' }}</span>
                </span>
              </q-item-section>
            </div>
          </div>
        </q-item>
        <q-item :clickable="false" style="padding: 0px 20%">
          <div class="row justify-around">
            <div class="col-4">
              <q-item-section>
                <span style="color: #5f77fd;display: inline-block" class="iconfont icontubiao-82">
                  <span style="color: black"> 角色</span>
                </span>
              </q-item-section>
            </div>
            <div class="col-4" style="text-align: right">
              <q-item-section>
                <span style="color: #5f77fd;display: inline-block;width: 100%">
                  <span style="color: black; width: 100%; margin-right: 0; margin-left: auto;" class="text-ellipsis">
                    {{ userInfos.roleNames ? userInfos.roleNames : '--' }}
                  </span>
                </span>
              </q-item-section>
            </div>
          </div>
        </q-item>
        <q-item :clickable="false" style="padding: 0px 20%" v-if="!isHuawei">
          <div class="row justify-around">
            <div class="col-4">
              <q-item-section>
               <span style="color: #5f77fd;display: inline-block" class="iconfont icontubiao-0">
                  <span style="color: black"> 密码</span>
                </span>
              </q-item-section>
            </div>
            <div class="col-4" style="text-align: right">
              <q-item-section>
                <span style="color: #5f77fd;display: inline-block">
                  <q-btn style="padding: 0px;font-size: 16px;min-height: 0px" flat color="primary" label="修改密码" @click="resetPassword" />
                </span>
              </q-item-section>
            </div>
          </div>
        </q-item>
      </q-list>
    </div>
    <div id="user-logout" class="btn-box">
      <div class="form-inline" style="padding: 30px 0 20px">
        <q-btn class="btn" unelevated type="submit" color="primary" label="退出登录" @click="logOut"/>
      </div>
    </div>
<!--    <div style="background-color: #fff;">-->
      <div class="text-center" style="font-size: 12px;color: #999;position: absolute;width: 100%;bottom: 0;">
        语祯物联科技(上海)有限公司
        <a href="https://www.mgm-iot.com" style="padding: 0 8px;color:#999;text-decoration: underline" target="_Blank">https://www.mgm-iot.com</a>
        语祯物联版权所有 copyright©2020
      </div>
<!--    </div>-->

  </div>

  <q-dialog class="add-edit-process-define dialog" v-model="show" persistent>
    <q-card style="min-width: 400px">
      <q-card-section class="dialog-title bg-primary">
        <div class="text-center text-white">修改密码</div>
      </q-card-section>
      <q-form @submit="submit" greedy class="q-gutter-md dialog-content">
        <q-card-section style="margin-bottom: 10px">
          <q-input
            :type="isOldPwd ? 'password' : 'text'"
            v-model="oldPassWord"
            placeholder="请输入旧密码"
            dense
            outlined
            :rules="[
                    val => val.length >= 6 && val.length <= 20 || '请输入6-20位密码',
                  ]"
          >
            <template v-slot:prepend>
              <i class="iconfont icontubiao-0" />
            </template>
            <template v-slot:append>
              <q-icon
                :name="isOldPwd ? 'visibility_off' : 'visibility'"
                class="cursor-pointer"
                @click="isOldPwd = !isOldPwd"
              />
            </template>
          </q-input>
          <q-input
            :type="isNewPwd ? 'password' : 'text'"
            v-model="newPassWord"
            placeholder="请输入新密码"
            dense
            outlined
            :rules="[
                    val => val.length >= 6 && val.length <= 20 || '请输入6-20位密码',
                  ]"
          >
            <template v-slot:prepend>
              <i class="iconfont icontubiao-0" />
            </template>
            <template v-slot:append>
              <q-icon
                :name="isNewPwd ? 'visibility_off' : 'visibility'"
                class="cursor-pointer"
                @click="isNewPwd = !isNewPwd"
              />
            </template>
          </q-input>
          <q-input
            :type="isAgainPwd ? 'password' : 'text'"
            v-model="againPassWord"
            placeholder="再次确认"
            dense
            outlined
            :rules="[
                    val => val === newPassWord || '两次输入不一致',
                  ]"
          >
            <template v-slot:prepend>
              <i class="iconfont icontubiao-0" />
            </template>
            <template v-slot:append>
              <q-icon
                :name="isAgainPwd ? 'visibility_off' : 'visibility'"
                class="cursor-pointer"
                @click="isAgainPwd = !isAgainPwd"
              />
            </template>
          </q-input>
        </q-card-section>
        <q-separator />
        <div class="dialog-footer text-center margin-t-10">
          <q-btn outline label="取消" color="primary" @click="close" class="q-mr-md"/>
          <q-btn unelevated label="确认" color="primary" type="submit"/>
        </div>
      </q-form>
    </q-card>
  </q-dialog>
  <service-time-dialog ref="serviceTimeDialog"></service-time-dialog>
  <ChangePhoneDialog :show="showChangePhone" @close="showChangePhone=false"/>
</div>
</template>

<script>
import { goLoginPage } from '../../permission'

const version = process.env.APP_VERSION
const versionType = process.env.VERSION_TYPE
import { getUser, editPassWord, editUser } from 'src/boot/home/user'
import { logout } from 'src/boot/login/login'
import { mapGetters, mapMutations } from 'vuex'
import userStep from 'src/assets/json/user-guide-file/user-step'
import Driver from 'driver.js' // import driver.js
import 'driver.js/dist/driver.min.css' // import driver.js css
import { removeToken, removeRefreshToken } from 'yz-help'
import ServiceTimeDialog from './components/service-time-dialog'
import ChangePhoneDialog from './components/change-phone-dialog'
import { uploadFlie } from 'src/boot/template/template-upload'
export default {
  name: 'user',
  computed: {
    ...mapGetters([
      'userInfo',
      'guideLines',
      'client'
    ]),
    isHuawei () {
      return this.userInfo.channel === 'hw' && this.userInfo.client_id === 'huawei_iot_stage_app'
    },
    isYQZZ () {
      return this.userInfo.channel === 'hw' && this.userInfo.client_id === process.env.YQZZ_CLIENT_ID
    },
    certified () {
      return this.userInfo.tenant_id !== 0
    }
  },
  data () {
    return {
      isOldPwd: true,
      isNewPwd: true,
      isAgainPwd: true,
      userId: '',
      oldPassWord: '', // 就密码
      newPassWord: '', // 新密码
      againPassWord: '', // 再次密码
      show: false,
      userInfos: [],
      version,
      fileName: null, // 文件名（用于订阅）
      versionType,
      showChangePhone: false
    }
  },
  created () {
    this.init()
    this.SET_GUIDELINES(false)
  },
  watch: {
    guideLines: {
      immediate: true,
      handler: function (val) {
        const driver = new Driver(this.CommonConfig.user_guide)
        this.$nextTick(() => {
          if (val) {
            driver.defineSteps(userStep)
            driver.start()
          }
          this.SET_GUIDELINES(false)
        })
      }
    }
  },
  methods: {
    ...mapMutations(['SET_GUIDELINES', 'SET_TOKEN', 'SET_REFRESHTOKEN', 'SET_PERMISSIONS', 'SET_USERPHOTO']),
    init () {
      this.userId = this.userInfo.user_id
      this.getUserId()
    },

    getUserId () {
      getUser(this.userId).then(res => {
        res.data.roleNames = res.data.roles.map(o => o.name).join(', ')
        this.userInfos = res.data
        this.SET_USERPHOTO(res.data.photoUrl)
      })
    },

    // 提交表单
    submit () {
      const query = {}
      query.newPassword = this.newPassWord
      query.oldPassword = this.oldPassWord
      editPassWord(query, this.userId).then(() => {
        this.$q.dialog({
          title: `<p class="dialog-notice-title"><i class="iconfont icontubiao-53"></i>
          修改成功，请重新登录`,
          html: true,
          ok: {
            unelevated: true,
            label: '确认'
          }
        })
          .onOk(() => {
            this.logOut()
          })
      })
    },

    // 解绑微信
    outWechat () {
      this.$q.dialog({
        title: `<p class="dialog-notice-title"><i class="iconfont icontubiao-28"></i>
          是否确定解绑微信</p>`,
        message: '解绑后不能再使用该微信账号登陆平台？',
        html: true,
        ok: {
          unelevated: true,
          label: '确认'
        },
        cancel: {
          unelevated: true,
          outline: true,
          label: '取消'
        }
      })
        .onOk(() => {
          this.$q.dialog({
            title: `<p class="dialog-notice-title">
      <i class="iconfont icontubiao-53" ></i> 正在拼命开发中...</p>`,
            html: true,
            ok: {
              unelevated: true,
              label: '确认'
            }
          })
        })
    },

    // 清空表单
    reset () {
      this.newPassWord = ''
      this.againPassWord = ''
      this.oldPassWord = ''
      this.isOldPwd = true
      this.isNewPwd = true
      this.isAgainPwd = true
    },

    // 打开重置密码弹出框
    resetPassword () {
      this.show = true
      this.reset()
    },

    // 关闭重置密码弹出框
    close () {
      this.show = false
    },

    // 退出登陆
    logOut () {
      this.$q.dialog({
        title: `<p class="dialog-notice-title"><i class="iconfont icontubiao-28"></i>
          是否确认退出登录`,
        html: true,
        ok: {
          unelevated: true,
          label: '确认'
        },
        cancel: {
          unelevated: true,
          outline: true,
          label: '取消'
        }
      })
        .onOk(() => {
          logout().finally(() => {
            removeToken()
            removeRefreshToken()
            this.disconnect()
            if (this.isHuawei) {
              window.location.href = `https://auth.iotstage.huaweicloud.com/logout?service=${process.env.DLP_PATH}?utm_source=huawei`
            } else if (this.isYQZZ) {
              window.location.href = `${process.env.YQZZ_AUTH_PAGE}/cas/logout?loginType=2&service=${process.env.DLP_PATH}?utm_source=yqzz`
            } else {
              goLoginPage()
            }
          })
        })
    },
    // 断开连接
    disconnect () {
      if (this.client) {
        this.client.disconnect(() => {
          console.log('断开连接')
        })
      }
    },

    // 上传照片
    _onUploadPhotoClick: function () {
      // 触发文件选择
      this.$refs.fileInput.dispatchEvent(new MouseEvent('click'))
    },

    // 选择照片
    onPhotoFileSelected () {
      if (!this.$utils.fileTypeHoldUp(this.$refs.fileInput.files[0].name, ['.jpg', '.jpeg', '.png'])) {
        return
      }
      this.$q.loading.show()
      let file = this.$refs.fileInput.files
      let fileSize = file[0].size
      let fileMaxSize = 1024 * 1024 * 5
      if (fileSize <= fileMaxSize) {
        const path = this.CommonConfig.ossFilePath.avatarImagesDir
        // let res = await this.$uploadPublicFile(file, path)
        let res = this.$getUploadPath(file, path)
        this.fileName = res.fileNameNew
        this.onSubscribe()
        uploadFlie(res.uploadPath, event.target.files[0], res.fileNameNew).then(res => {
          if (res.code !== '1200') {
            this.$showErrTips('上传失败，请稍后重试')
            this.closeUbscribeTopic()
          }
        }).catch(res => {
          console.log(res)
          this.closeUbscribeTopic()
        })
      } else {
        this.$q.dialog({
          title: `<p class="dialog-notice-title">
      <i class="iconfont icontubiao-53" ></i> 文件大小不能超过5M</p>`,
          html: true,
          ok: {
            unelevated: true,
            label: '确认'
          }
        })
      }
      this.$refs.fileInput.value = null
    },
    onMessageArrived (message) {
      let msg = JSON.parse(message.body).data
      if (msg.requestId !== this.fileName) {
        return
      }
      if (msg.code + '' !== '200') {
        this.$showErrTips('上传失败，请稍后重试')
        this.closeUbscribeTopic()
        return
      }
      editUser(this.userId, msg.data).then(() => {
        this.closeUbscribeTopic()
        this.getUserId()
      }).catch(res => {
        console.log(res)
        this.closeUbscribeTopic()
      })
    },
    onSubscribe () {
      if (this.client) {
        this.client.subscribe(
          `${this.CommonConfig.socketConfig.SOCKET_TOPIC.uploadFile.subscribeTopic}${this.fileName}`, this.onMessageArrived, { id: `${this.fileName}` }
        )
      } else {
        setTimeout(() => {
          this.onSubscribe()
        }, 200)
      }
    },
    closeUbscribeTopic () {
      this.client.unsubscribe(`${this.fileName}`)
      this.$q.loading.hide()
    },
    // 显示服务期限弹框
    showServiceTimeDialog () {
      this.$refs.serviceTimeDialog.showDialog()
      this.$refs.serviceTimeDialog.getServicePeriod(this.userId)
    }
  },
  components: {
    ServiceTimeDialog,
    ChangePhoneDialog
  }
}
</script>

<style scoped lang="stylus">
  .iconfont{
    font-size 18px
    &>span{
      font-size 16px
      margin-left 10px
    }
  }
  .user {
    .bg {
      width 100%
      height 200px
      background-image url("../../statics/img/user-bg.png")
      background-repeat no-repeat
      background-size 100% 100%
      -moz-background-size 100% 100%
      border-top-left-radius 6px
      border-top-right-radius 6px
      border-bottom-right-radius 0em
      border-bottom-left-radius 0em
      .title {
        display flex
        justify-content center
        align-items center
        height 200px
        flex-direction column
        .avatar {
          width 130px
          height 130px
          border-radius 50%
        }
      }
    }
    .body {
      /*height 500px*/
      background-color white
      width: 100%
      font-size 16px
    }
    .btn-box {
      display flex
      justify-content center
      align-items center
      background-color white
    }
  }
  .row {
    width 100%
  }

  .row > div
    padding: 5px
  .doc-container > div + div
    margin-top: 1rem

  .photo-box {
    display flex
    justify-content center
    align-items center
    justify-content space-between

    .photo {
      height 130px
      width 130px
      border 1px solid #D3D3D3
      border-radius 50%
    }
    .upload-btn {
      height 130px
      width 130px
      border-radius 50%
      overflow hidden
      &.dashed-border{
        background #d0d6fb
      }

      &.dashed-border:after {
        $border-padding = 28px

        content ""
        display block
        position absolute
        top 0
        left 0
        height "calc(100% - %s)" % $border-padding
        width "calc(100% - %s)" % $border-padding
        margin ($border-padding / 2)
      }
    }
  }
</style>
